package org.bright.service.Impl;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.bright.dao.ProductDao;
import org.bright.entity.Product;
import org.bright.service.ProductService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Override
    public List<Product> getProductList(String productName) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mySqlConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ProductDao productDao = sqlSession.getMapper(ProductDao.class);
        return productDao.getProducts(productName);
    }

    @Override
    public int insertProduct(Product product) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mySqlConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ProductDao productDao = sqlSession.getMapper(ProductDao.class);
        return productDao.insertProduct(product);
    }

    @Override
    public int deleteProductById(int id) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mySqlConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ProductDao productDao = sqlSession.getMapper(ProductDao.class);
        return productDao.deleteProductById(id);
    }

    @Override
    public int updateProduct(Product product) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mySqlConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ProductDao productDao = sqlSession.getMapper(ProductDao.class);
        return productDao.updateProduct(product);
    }
}
